//
//  OAuthViewController.swift
//  MQWeibo
//
//  Created by SYN on 15/11/14.
//  Copyright © 2015年 SYN. All rights reserved.

/**
App Key：4222379268
App Secret：eeab41414e6847599a586a8026b1256f

https://api.weibo.com/oauth2/authorize?client_id=4222379268&redirect_uri=http://zmq930619.imwork.net/
*/

import UIKit

import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    let WB_Client_Id = "4222379268"
    
    let WB_Redirect_Uri = "http://zmq930619.imwork.net/"
    
    let WB_Client_Secret = "eeab41414e6847599a586a8026b1256f"
    
    /// 计算属性,只有getter,是ReadOnly
//    var webView: UIWebView {
//        
//        return view as! UIWebView
//        
//    }
    var webView = UIWebView()

    override func loadView() {
        view = webView
        
        webView.delegate = self
    }


    @IBAction func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        loadOAuthPage()

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        SVProgressHUD.dismiss()
    }
    /**
    加载授权页面
    */
    private func loadOAuthPage(){
        
//        view = webView
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        
        let url = NSURL(string: urlString)!
        
        webView.loadRequest(NSURLRequest(URL: url))
        
    }
    
    //如果系统方法返回true ,都能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request.URL)
        
        //取到url的完整字符串
        let urlString = request.URL!.absoluteString
        
        //如果是官方的页面继续加载
        if urlString.hasPrefix("https://api.weibo.com/"){
            return true
        }
        //判断url是否是设置的回调地址
        if !urlString.hasPrefix(WB_Redirect_Uri){
            return false
        }
        //代码执行到这里一定是回调地址
//        print("*******",urlString)
        
        //query可以滤掉协议头和主机地址
        let codeStr = "code="
        
        let query = request.URL!.query!
        
        if query.hasPrefix(codeStr){
            //获取请求码
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            
//            print("验证码" + code)
            
            loadAccessToken(code)
            
        }else{
            print("用户拒绝")
            //直接关闭视图控制器
            close()
        }
        
        return false
        
    }
    
    private func loadAccessToken(code:String){
        let params = [
            "client_id":WB_Client_Id,
            "client_secret":WB_Client_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_Uri,
        ]
        UserAccount.loadAccessToken(params) { (account, error) -> () in
            
            if account != nil {
                //设置全局变量
                shareUserAccount = account
                
                print("账户信息------>\(account)")
                return
            }
            
            //错误处理
            SVProgressHUD.showInfoWithStatus("错误")
            //为了调试用
            print(error)
        }
    }
    //开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    //页面加载完成
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
         
    }

}
